from flask import Flask, send_from_directory, jsonify
from pathlib import Path
import json

app = Flask(__name__)
app.config['ROOT_DIR'] = Path(__file__).parent.resolve()

def create_response(data, status=200):
    """标准API响应格式化工具"""
    return jsonify({"status": status, "data": data}), status

@app.route('/')
def index():
    """带缓存刷新的主路由"""
    response = send_from_directory('templates', 'index.html', max_age=0)
    response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0'
    return response

@app.route('/api/mods')
def get_mods():
    """稳健数据接口"""
    try:
        file_path = app.config['ROOT_DIR'] / 'modpacks.json'
        
        # 严格路径存在性检查
        if not file_path.exists():
            return create_response(None, 404), 404
            
        # 智能编码检测读取
        with open(file_path, 'r', encoding='utf-8') as f:
            return create_response(json.load(f))
            
    except json.JSONDecodeError:
        error_msg = "JSON文件格式错误，请检查爬虫输出"
        print(f"[ERROR] {error_msg}")
        return create_response(error_msg, 500)
    except Exception as e:
        print(f"[CRITICAL] 严重错误：{str(e)}")
        return create_response(str(e), 500)

if __name__ == '__main__':
    app.run(debug=True, port=5000)
